package com.shiro.demo.framework.captcha;

import lombok.Data;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@Data
public class CaptchaAuthFilter extends AccessControlFilter {
    public CaptchaAuthFilter(boolean enabled, String type){
        this.enabled = enabled;
        this.type = type;
    }

    //是否使用验证码过滤器
    private boolean enabled;
    //验证码类型：text or math
    private String    type;

    /**
     * 验证验证码是否正确
     * @param servletRequest
     * @return
     */
    protected boolean validateRequest(ServletRequest servletRequest){
        if(!enabled) return true;

        //客户端传递的code与Session的code是否保持一致
        Object captcha = servletRequest.getParameter("captcha");
        if(!StringUtils.isEmpty(captcha)){
            String code = (String)SecurityUtils.getSubject().getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            if(captcha.toString().compareToIgnoreCase(code) == 0){
                return true;
            }
        }
        return false;
    }

    /**
     * 该过滤器首先调用本函数，返回false则调用onAccessDenied()
     * @param servletRequest
     * @param servletResponse
     * @param o
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) {
        servletRequest.setAttribute(Constants.CAPTCHA_ENABLED, enabled);
        servletRequest.setAttribute(Constants.CAPTCHA_TYPE, type);
        return validateRequest(servletRequest);
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {
        servletRequest.setAttribute(Constants.CAPTCHA_AUTH_FAILED, true);
        return true;
    }
}
